package com.yeskery.nut.extend.oauth;

/**
 * 基础的授权码生成器
 * @author YESKERY
 * 2024/10/21
 */
public abstract class BaseAuthorizationCodeGenerator implements AuthorizationCodeGenerator {

    /** token保存接口 */
    private final TokenStore tokenStore;

    /** token过期时间 */
    private final long expires;

    /**
     * 构造基础的授权码生成器
     * @param tokenStore token保存接口
     * @param expires token过期时间
     */
    public BaseAuthorizationCodeGenerator(TokenStore tokenStore, long expires) {
        this.tokenStore = tokenStore;
        this.expires = expires;
    }

    @Override
    public String generateAuthorizationCode(String value) {
        String authorizationCode = createAuthorizationCode();
        tokenStore.save(getPrefix() + authorizationCode, value, expires);
        return authorizationCode;
    }

    @Override
    public String getAuthorizationCodeValue(String authorizationCode) {
        String code = getPrefix() + authorizationCode;
        return tokenStore.get(code);
    }

    @Override
    public boolean validateAuthorizationCode(String authorizationCode) {
        String code = getPrefix() + authorizationCode;
        return tokenStore.validate(code);
    }

    @Override
    public void deleteAuthorizationCode(String authorizationCode) {
        String code = getPrefix() + authorizationCode;
        tokenStore.delete(code);
    }

    /**
     * 获取token前缀
     * @return token前缀
     */
    protected String getPrefix() {
        return "nut:oauth:authorization_code:";
    }

    /**
     * 创建授权码
     * @return 授权码
     */
    protected abstract String createAuthorizationCode();
}
